//Check for broken images in a page

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrokenImagesOfPage {

	WebDriver myFD = new FirefoxDriver();
	String vURL = "http://www.myurl.com";
	@Test
	public void checkforbrokenimages() throws Exception{
		
		myFD.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		myFD.get(vURL);  
		//myFD.findElement(By.name("q")).sendKeys("Test"); 
		
		List<WebElement> imagesList = myFD.findElements(By.tagName("img"));
		int countBrokenImages = 0;
		for (WebElement image : imagesList)
		{
		    HttpResponse response = new DefaultHttpClient().execute(new HttpGet(image.getAttribute("src")));
		    if (response.getStatusLine().getStatusCode() != 200){
		        // Do whatever you want with broken images
		    	String  currentImageUrl = image.getAttribute("src");
		    	System.out.println(currentImageUrl);
		    	countBrokenImages++;
		    }
		}	
		System.out.println("The number of Broken URLs are: " + countBrokenImages);
}
}
//I will find the webelemets whos tag name is img and prepare list of this webelements 
//using HttpResponse from DefaultHttpClient by executing the httpget response of the 
//image src, I will check if the response status code not equal to 200
//and get the image URL
//By looping the httprespose for all the list of image elements, I can get the broken images